package edu.gatech.oad.antlab.m7final;
import java.awt.Component;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import net.miginfocom.swing.MigLayout;
import java.awt.event.*;
import java.util.ArrayList;

/**
 * The StorePanelM6 class Is the main display that holds the other panels and the listeners
 * @author It's A Trap
 *
 */
public class StorePanelM6 extends JPanel {

	private JButton[] buttons;
	private JTextField[] holder;
	private WagonInventory wagonInv;
	private StoreInventory storeInv;
	private MoneyPanelM6 moneyPanelM6;
	private StoreInventoryPanel storeInventoryPanel;
	private WagonInventoryPanel2 wagonInventoryPanel2;
	private ArrayList<Item> items;
	private JLabel[] wagonLabels;
	private JLabel[] labels;
	private int total = 0;
	ArrayList<Item> itemList; 
	WagonWtPanelM6 wagonWtPanelM6;
	/**
	 * This is the panel holding the components of the Store.
	 * 
	 * @author Amy Lambeth
	 * @version 1.0 10/17/2011
	 */

	private static final long serialVersionUID = 1L;
	StoreController controller;
	/**
	 * Create the panel.
	 */
	public StorePanelM6() {
		itemList = new ArrayList<Item>();
		itemList.add(new Item("Oxen",0,0, 40));
		itemList.add(new Item("Food",0,0, 1));
		itemList.add(new Item("Clothing",0,0, 10));
		itemList.add(new Item("Ammunition Box x20",0,0, 2));
		itemList.add(new Item("Wheels",0,0, 10));
		itemList.add(new Item("Axle",0,0, 10));
		itemList.add(new Item("Tongue",0,0, 10));
		controller = new StoreController(Wagon.getInventoryController(),60); // independence store
		wagonInv = controller.getWagonInventory();
		storeInv = controller.getStoreInventory();


		setLayout(new MigLayout("", "[300.00,grow][130.00,grow][325.00,grow]", "[36.00][38.00][298.00,grow][118.00,grow]"));

		JLabel lblStoreInventory = new JLabel("Store Inventory");
		add(lblStoreInventory, "cell 0 1,alignx center");

		JLabel lblTrade = new JLabel("Trade");
		add(lblTrade, "cell 1 1,alignx center");

		JLabel lblWagonInventory = new JLabel("Wagon Inventory");
		add(lblWagonInventory, "cell 2 1,alignx center");

		storeInventoryPanel = new StoreInventoryPanel(controller.getStoreInventory());
		add(storeInventoryPanel, "cell 0 2,grow");

		TradePanelM6 tradePanelM6 = new TradePanelM6();
		add(tradePanelM6, "cell 1 2,alignx center,growy");

		wagonInventoryPanel2 = new WagonInventoryPanel2(controller.getWagonInventory());
		add(wagonInventoryPanel2, "cell 2 2,grow");

		moneyPanelM6 = new MoneyPanelM6();
		add(moneyPanelM6, "cell 0 3,grow");

		labels = storeInventoryPanel.getQuantityLabels();

		wagonLabels = wagonInventoryPanel2.getQuantityLabels();
		StoreButtonPanel storeButtonPanel = new StoreButtonPanel();
		add(storeButtonPanel, "cell 1 3,alignx center,growy");

		wagonWtPanelM6 = new WagonWtPanelM6(controller.getWagonInventory());
		add(wagonWtPanelM6, "cell 2 3,grow");

		items = new ArrayList<Item>();

		Component[] action = tradePanelM6.getComponents();

		TextListener textListen = new TextListener();
		holder = new JTextField[7];
		int index = 0;
		for(Component temp: action){
			if(temp instanceof JTextField){
				holder[index] = (JTextField) temp;
				holder[index].getDocument().addDocumentListener(textListen);
				index++;

			}	
		}

		Component[] buyselltrade = storeButtonPanel.getComponents();
		buttons = new JButton[3];
		index = 0;
		ButtonListener buttonListener = new ButtonListener();
		for(Component temp2: buyselltrade){
			if(temp2 instanceof JButton){
				buttons[index] = (JButton) temp2;
				buttons[index].addActionListener(buttonListener);
				index++;
			}
		}
	}
	
	/**
	 * Tracks the cost of the active purchases
	 */
	public void QuantityChanged(){
		total = 0;
		int index = -1;
		for (JTextField change: holder){
			index++;
			try{
				if(!change.getText().equals("")){

					int temp = Integer.parseInt(change.getText());
					temp = temp * wagonInv.get(index).getPRICE();
					total = total + temp;
					moneyPanelM6.updateCost(total);

				}
			}
			catch(Exception e){
				JOptionPane.showMessageDialog(null,"Invalid character Entered.","Enter valid character", JOptionPane.WARNING_MESSAGE);
			}

		}

	}

	/**
	 * Buys the appropriate amount of items from the text fields
	 */
	public void buyItems(){
		for(int i =0; i <7;i++){
			if (!holder[i].getText().equals("") && !holder[i].getText().equals("0")  ){
				Item toBuy = itemList.get(i);
				controller.buyItem(toBuy, Integer.parseInt(holder[i].getText()));
				updateLabels();	
			}
		}
	}
	
	/**
	 * Sells the appropriate amount of items from the text fields
	 */
	public void sellItems(){

		for(int i =0; i <7;i++){
			if (!holder[i].getText().equals("0")){
				Item toSell = itemList.get(i);
				controller.sellItem(toSell, Integer.parseInt(holder[i].getText()));
				updateLabels();	
			}
		}
	}
	
	/**
	 * Updates the labels of the quantities
	 */
	public void updateLabels(){

		for(int i = 0; i<7;i++){
			labels[i].setText(""+ (storeInv.get(i).getQuantity()));
			wagonLabels[i].setText("" + (wagonInv.get(i).getQuantity()));
		}
	}
	
	/**
	 * Calculates the weight of the wagon
	 * @return the weight of the wagon
	 */
	public int updateWeight(){
		int total = 0;

		for(int i = 0;i < 7;i++){
			int quantityAsked = Integer.parseInt(holder[i].getText());
			if(quantityAsked > 0){
				total = total + (quantityAsked * wagonInv.get(i).getWEIGHT_INDIVIDUAL());

			}
		}
		return total;
	}

	public  int calculateWeight(){
		int totalWeight = 0;
		for(Item temp: items){
			totalWeight = totalWeight + temp.getTotalWeight();
		}
		return totalWeight;
	}
	
	/**
	 * Listener for the Textfields
	 *
	 */
	private class TextListener implements DocumentListener{

		public void insertUpdate(DocumentEvent e) {
			QuantityChanged();
		}

		public void removeUpdate(DocumentEvent e) {
			QuantityChanged();
		}

		public void changedUpdate(DocumentEvent e) {
			QuantityChanged();
		}
	}

	/**
	 * Listener for the JButtons
	 * 
	 */
	private class ButtonListener implements ActionListener{

		public void actionPerformed(ActionEvent e){



			boolean quantitiesCorrect = true;
			boolean sellQuantitiesCorrect = true;
			int temp = 0;

			for(JTextField info : holder){

				if(info.getText().equals(""))
					info.setText("0");
				if(Integer.parseInt(info.getText()) > Integer.parseInt(labels[temp].getText())){
					quantitiesCorrect = false;
				}
				if(Integer.parseInt(info.getText()) > Integer.parseInt(wagonLabels[temp].getText())){
					sellQuantitiesCorrect = false;
				}
				
				temp++;	
			}
			
			if(e.getSource()== buttons[0]){	//buy clicked
				if (quantitiesCorrect) {
					if(Integer.parseInt(moneyPanelM6.getCost())> Integer.parseInt(moneyPanelM6.getMoneyLeft()))//checking money
						JOptionPane.showMessageDialog(null,"Not enough money, take out some items.","Weight Error", JOptionPane.WARNING_MESSAGE);
					
					else{	//check weight
						//System.out.println(calculateWeight() + "   " + wagonInv.getCurWeight()); // not working
						if (calculateWeight() + wagonInv.getCurWeight()> wagonInv.getCapacity()) //if they are buying more than we can hold
							JOptionPane.showMessageDialog(null,"Wagon weight exceeded, take out some items.","Weight Error", JOptionPane.WARNING_MESSAGE);
						else{
							buyItems();
							wagonInv.setMoney(wagonInv.getMoney()- total);
							moneyPanelM6.updateMoneyLeft(wagonInv.getMoney());
							int newWeight = updateWeight();
							wagonWtPanelM6.updateWeightAdded(Integer.parseInt(wagonWtPanelM6.getWeight()) + newWeight);

						}
					}
				}
				else	//Request too many items from store
					JOptionPane.showMessageDialog(null,"Store does not have enough items that you are trying to buy.","Quantity Error", JOptionPane.WARNING_MESSAGE);
			}
			

			if(e.getSource()==buttons[1]){ //sell button clicked
				if(sellQuantitiesCorrect){
					sellItems();
					moneyPanelM6.updateMoneyLeft(wagonInv.getMoney());
					wagonInv.setMoney(wagonInv.getMoney()+ total);
					moneyPanelM6.updateMoneyLeft(wagonInv.getMoney());
					int change = updateWeight();
					int nowWeight=Integer.parseInt(wagonWtPanelM6.getWeight()) - change;
					wagonWtPanelM6.updateWeightAdded(nowWeight);
				}
					else
					JOptionPane.showMessageDialog(null,"You do not have enough items to sell.","Quantity Error", JOptionPane.WARNING_MESSAGE);
					
			}
		}
	}
}


